package com.allen.control;

import com.allen.bean.Instore;
import com.allen.service.InstoreService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/instoreCtrl")
public class InstoreControl extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String parm = req.getParameter("parm");
        switch (parm) {
            case "list":
                list(req, resp);
                break;
            case "select":
                select(req, resp);
                break;
            case "plus":
                plus(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "detail":
                detail(req, resp);
        }
    }

    private void detail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Instore instore = new InstoreService().detail(req, resp);
        req.setAttribute("instore", instore);
        req.getRequestDispatcher("/instore/detail.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {

        new InstoreService().add(req, resp);
    }

    private void plus(HttpServletRequest req, HttpServletResponse resp) {
        int num = Integer.parseInt(req.getParameter("num"));
        int gid = Integer.parseInt(req.getParameter("gid"));
        int number = new InstoreService().limit(gid);
        num = number + num;
        new InstoreService().updateNum(num, gid);
    }

    private void select(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String json = new InstoreService().getGoodsJson();
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(json);
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Instore> outstores = new InstoreService().getAllInstore();
        req.setAttribute("instores", outstores);
        req.getRequestDispatcher("/instore/list.jsp").forward(req, resp);
    }
}
